﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin;

[Area("Admin")]
[Authorize]
public class ContentController : Base
{
    private readonly LoginUtil _LoginUtil;
    private readonly ContentService _contentService;
    private readonly ContentCateService _contentCateService;
    private readonly ConfigService _configService;
    private readonly AttmentService _attment;
    private readonly LogService _logService;
    private readonly AdminUserService _adminUserService;
    public ContentController(LoginUtil LoginUtil, ContentService contentService, ContentCateService contentCateService,
        LogService logService, AttmentService attmentService, ConfigService configService, AdminUserService adminUserService)
    {
        _LoginUtil = LoginUtil;
        _contentService = contentService;
        _contentCateService = contentCateService;
        _configService = configService;
        _attment = attmentService;
        _logService = logService;
        _adminUserService = adminUserService;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="cid"></param>
    /// <param name="searchcid">用于判断是否搜索CID</param>
    /// <param name="keyword"></param>
    /// <param name="stat">2 为所有内容 1 已经审核  0 草稿</param>
    /// <param name="page"></param>
    /// <param name="limit"></param>
    /// <param name="json">判断是否获取列表  1  0</param>
    /// <returns></returns>
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_Index)]
    public async Task<IActionResult> IndexAsync(string cid, string keyword, string searchcid, int stat = 2, int page = 1, int limit = 15, int json = 0)
    {
        UserInfo adminUser = await _LoginUtil.UserInfoAsync();
        if (json == 1)
        {

            ContentQuery contentQuery = new()
            {
                Cid = searchcid ?? cid,
                CurrentPage = page,
                Limit = limit,
                Uid = adminUser.UserId,
                Title = keyword,
                Status = stat,
                Uids = await _adminUserService.AdminPostAsUids(adminUser)
            };


            var pagedList = await _contentService.GetListByCidAdminAsync(contentQuery);
            return Json(new { code = 0, count = pagedList.TotalItems, data = pagedList.Items });
        }
        ViewBag.cid = cid;
        ViewBag.catelist = await _contentCateService.GetContentCateListAsync(adminUser, 1);
        return View();

    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_AddOrEdit)]
    public async Task<IActionResult> AddOrEditAsync(int id, int edit = 0, int cid = 0)
    {
        if (edit == 1)
        {
            EditContentAndContent data = await _contentService.GetEditAsync(id);
            List<ViewAttment> attments = null;
            if (!string.IsNullOrEmpty(data.Attments))
                attments = await _attment.GetListAsync(data.Attments);
            return Json(new { status = 1, data, attments });
        }
        //附件信息
        SytemConfig configSiteInfo = await _configService.GetByNameAsync();
        ViewBag.fileExts = configSiteInfo.FileExt;
        ViewBag.fileSize = configSiteInfo.FileSize;
        //栏目信息
        UserInfo adminUser = await _LoginUtil.UserInfoAsync();
        ViewBag.contentCateData = await _contentCateService.GetCategorySelectListItemsAsync(adminUser.DeptId,adminUser.Gid, 1);
        ViewBag.cid = cid;
        //内容信息
        ViewBag.id = id;
        ViewBag.uid = adminUser.UserId;
        return View();

    }

    [HttpPost, ActionName("CreatePost")]
    [XssFieldFilter]//防Xss
    [ActionPermissionFilter(Permission = PermissionKeys.Content_AddOrEdit)]
    [Log(Name = "新增文章")]
    public async Task<IActionResult> CreatePostAsync(EditContentAndContent contentPost)
    {
        if (ModelState.IsValid)
        {
            UserInfo adminUser = await _LoginUtil.UserInfoAsync();

            Content content = contentPost.AsContent();
            content.Uid = adminUser.UserId;

            Content contentRes = await _contentService.InsertContentAndContentAsync(content, contentPost.AsContentContent());

            if (contentRes.Id > 1)
            {
                return Json(new { status = 1, msg = "新增内容 Id: " + contentRes.Id, cid = contentRes.Cid });
            }
            else
                return Json(new { status = 0, msg = "新增失败！" });
        }
        else
        {
            var error = ModelState.GetErrorMessages();
            return Json(new { result = 0, msg = error });
        }
    }


    [HttpPost, ActionName("EditPost")]
    [XssFieldFilter]//防Xss
    [ActionPermissionFilter(Permission = PermissionKeys.Content_AddOrEdit)]
    [Log(Name = "修改文章")]
    public async Task<IActionResult> EditPostAsync(EditContentAndContent contentPost)
    {
        if (ModelState.IsValid)
        {
            int x = await _contentService.UpdateContentAndContentAsync(contentPost.AsContent(), contentPost.AsContentContent());
            if (x > 0)
            {
                return Json(new { status = 1, msg = "修改内容 ID：" + contentPost.Id, cid = contentPost.Cid });
            }
            else
            {
                return Json(new { status = 0, msg = "修改失败！" });
            }
        }
        else
        {
            var error = ModelState.GetErrorMessages();
            return Json(new { status = 0, msg = error });
        }
    }
    [HttpPost]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_Status)]
    [Log(Name = "设置文章属性")]
    public async Task<IActionResult> SwitchStatus(int id, int status, string att)
    {
        if (await _contentService.UpdateContentAttAsync(id, status, att) > 0)
        {
            return Json(new { status = 1, msg = "设置属性 ID：" + id });
        }
        else
            return Json(new { status = 0, msg = "设置失败！" });
    }
    [HttpPost]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_Delete)]
    [Log(Name = "删除文章")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _contentService.DelContentAndContentAsync(id) > 0)
        {
            return Json(new { status = 1, msg = "删除内容 ID：" + id });
        }
        else
            return Json(new { status = 0, msg = "删除失败！" });
    }
}
